const { load, save, STORAGE_KEYS } = require('./storage.js')

function ensureLawyerData() {
  const seeded = load(STORAGE_KEYS.lawyers)
  if (seeded && Array.isArray(seeded)) return seeded
  
  const demo = [
    {
      id: 'L001',
      name: '王律师',
      firm: '北京市某某律师事务所',
      phone: '13800000001',
      email: 'wang@lawfirm.com',
      fields: ['合同纠纷', '知识产权'],
      verified: true
    },
    {
      id: 'L002',
      name: '刘律师',
      firm: '北京市某某律师事务所',
      phone: '13800000002',
      email: 'liu@lawfirm.com',
      fields: ['刑事辩护', '交通事故'],
      verified: true
    },
    {
      id: 'L003',
      name: '张律师',
      firm: '上海某某律师事务所',
      phone: '13900000001',
      email: 'zhang@lawfirm.com',
      fields: ['劳动争议', '婚姻家庭'],
      verified: true
    },
    {
      id: 'L004',
      name: '李律师',
      firm: '广州某某律师事务所',
      phone: '13700000001',
      email: 'li@lawfirm.com',
      fields: ['行政诉讼', '公司法务'],
      verified: false
    }
  ]
  
  save(STORAGE_KEYS.lawyers, demo)
  return demo
}

function getLawyers() {
  return ensureLawyerData()
}

function getLawyerById(id) {
  const lawyers = ensureLawyerData()
  return lawyers.find(lawyer => lawyer.id === id) || null
}

function shareCaseToLawyer(caseId, lawyerId) {
  const shares = load(STORAGE_KEYS.shares, {})
  if (!shares[caseId]) {
    shares[caseId] = []
  }
  if (!shares[caseId].includes(lawyerId)) {
    shares[caseId].push(lawyerId)
    save(STORAGE_KEYS.shares, shares)
  }
  return shares[caseId]
}

function getCaseShares(caseId) {
  const shares = load(STORAGE_KEYS.shares, {})
  return shares[caseId] || []
}

module.exports = {
  getLawyers,
  getLawyerById,
  shareCaseToLawyer,
  getCaseShares
}
